import { isEmpty, convertValue, permil } from '@/utils/util';

export default {

  // 设置y轴标签
  setYAxisLabel(option, property) {
    const { type } = option.yAxis;
    if (type === 'category' || type === 'value') {
      option.yAxis.axisLabel.formatter = (value, index) => {
        let label = property.yAxisLabel.tpl;
        label = this.parseAxisLabel(value, label, 'y');
        if (type === 'value') {
          label = permil(label);
        }
        return label;
      };
    }

    const rich = JSON.parse(JSON.stringify(property.yAxisLabel.rich || {}));
    for (const i in rich) {
      if (!rich[i]._hasWidth) {
        delete rich[i].width;
      }
    }
    option.yAxis.axisLabel.rich = rich;
  },

  /*
   * x轴或y轴自定义格式标签
   * parseAxisLabel('吉利莲,300', '${y[0]} - ${$y[1]}') => '吉利莲 - 300'
   */
  parseAxisLabel(value, format = '', v = 'y') {
    const _format = format.trim();
    if (!_format || _format === `\${${v}}`) {
      return `{${v}|${value}}`;
    }
    let _value = `${value}`;
    const emptyStrs = ['undefined', 'null', 'true', 'false'];
    if (emptyStrs.includes(_value)) {
      _value = '';
    }
    const _var = _value.split(',').filter(n => n);
    let str = _format;
    str = str.replace(/\$\{([^\}]*)\}/g, n => {
      if (n === `\${${v}}`) {
        return `{${v}|${_value}}`;
      }
      const match = n.match(/\d+/g);
      if (!match) {
        return '';
      } else {
        const i = match[0];
        if (isEmpty(_var[i])) {
          _var[i] = '';
        }
        return `{${v}${i}|${_var[i]}}`;
      }
    });
    return str;
  },
};
